<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>clone函数</title>
</head>
<body>
  <script>
    // 最后的clone函数，可以对js中的5种主要数据类型Number,String,Boolean,Object(Array)进行赋值

    var book = {
      name:"妙味修炼之道",
      picture: {
        small:'../这是小的',
        middle:'../这是中等的',
        large:'../这是大的',
      },
      arr: [1,2,3],
      fun: function(){
        console.log(1)
      },
      value: null
    }

    function clone(obj) {
      var newObj = null; //可以针对基本数据
      if (typeof obj == 'object' && obj !== null) { // 引用类型,数组，对象
        newObj = obj instanceof Array ? [] : {}
        for (var i in obj) {
          newObj[i] = clone(obj[i])
        }

      }else{ // 基本类型，function也是走这里
        newObj = obj;
      }
      return newObj;
    }

    var book2 = clone(book);
    book.name = '任重而道远';
    book.picture.small = 'small-small';
    console.log(book);
    console.log(book2);
  </script>
</body>
</html>